package com.jh3502.vivo.base;

import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.jh3502.vivo.Jh3502HelperApplication;
import com.jh3502.vivo.utils.Constant;
import com.jh3502.vivo.utils.eventbus.EventBusMessage;
import com.jh3502.vivo.view.SnackbarUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;

import static org.greenrobot.eventbus.EventBus.TAG;

/**
 * @author harisucici
 * @date 07.03
 */
public abstract class BaseFragment<V, T extends BasePresenter<V>> extends Fragment implements BaseView {
    public Jh3502HelperApplication mJh3502HelperApplication;
    @Nullable
    public Context mContext;
    @Nullable
    public BaseActivity mActivity;
    public boolean isVisible, isPrepared;
    public File mCamareFile;
    //输出数据展示
    @NonNull
    public List<BluetoothGattService> mGattServices = new ArrayList<>();
    //设备特征值集合
    @NonNull
    public List<List<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<>();
    protected T mPresenter;
    @Nullable
//    protected ProgressDialog progressDialog;
    protected View rootView;
    private ProgressDialog progressDialog;
    //设备信息

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mJh3502HelperApplication = (Jh3502HelperApplication) getActivity().getApplication();
        if (rootView == null) {
            mPresenter = initPresenter();
            if (progressDialog == null) {
                progressDialog = new ProgressDialog();
            }
//            progressDialog = new ProgressDialog();
            mContext = getContext();
            mActivity = (BaseActivity) getActivity();
            rootView = inflater.inflate(setViewId(), container, false);
            isPrepared = true;
            ButterKnife.bind(this, rootView);
            EventBus.getDefault().register(this);
            initView();
            initData();
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = getUserVisibleHint();
        if (!isPrepared || !isVisible) {
            return;
        }
        if (isPrepared) {
            if (getUserVisibleHint()) {
                isVisible = true;
                if (!EventBus.getDefault().isRegistered(this)) {
                    EventBus.getDefault().register(this);
                }
                doOnVisible();
            } else {
                isVisible = false;
                doOnInvisible();
            }
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        if (mPresenter != null) {
            mPresenter.attachView((V) this);
        }
        doOnResume();
        Log.i("BaseFragment_Me", "onResume");
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        doOnDestroy();
        EventBus.getDefault().unregister(this);
        Log.i("BaseFragment_Me", "onDestroyView");
    }

    public abstract T initPresenter();

    protected abstract int setViewId();

    protected abstract void initView();

    protected abstract void initData();

    protected abstract void doOnDestroy();

    protected abstract void doOnResume();

    protected abstract void doOnVisible();

    protected abstract void doOnInvisible();

    protected abstract void doOnSaveInstanceState(Bundle savedInstanceState);

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        doOnSaveInstanceState(savedInstanceState);
    }

    //    @Override
//    public void showLoadingDialog() {
//        progressDialog.show(mActivity.getSupportFragmentManager(),"1");
//        showLoadingDialog(null, null);
//    }
    @Override
    public void showLoadingDialog() {
        //        showLoadingDialog(null, "请等待");
        if (progressDialog.getTag() == null) {
            progressDialog.show(mActivity.getSupportFragmentManager(), "progress");
        }
    }

//    public void showLoadingDialog(String title, String message) {
//        if (mProgressDialog == null) {
//            mProgressDialog = new ProgressDialog(getActivity());
//            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//        }
//
//        if (title == null) {
//            title = "";
//        }
//        if (message == null) {
//            message = "";
//        }
//
//        mProgressDialog.setTitle(title);
//        mProgressDialog.setMessage(message);
//        mProgressDialog.show();
//    }


    //    @Override
//    public void dismissLoadingDialog() {
//        if (mProgressDialog != null && mProgressDialog.isShowing()) {
//            mProgressDialog.dismiss();
//        }
//        progressDialog.dismiss();
//    }
    @Override
    public void dismissLoadingDialog() {
        //        if (mProgressDialog != null && mProgressDialog.isShowing()) {
        //            mProgressDialog.dismiss();
        //        }
        if (progressDialog != null) {
            progressDialog.dismiss();
        }

    }

    @Subscribe
    public void onEventMainThread(@NonNull EventBusMessage eventBusMessage) {
        Log.i(TAG, "onEventMainThread: " + eventBusMessage.toString());
    }

    @Nullable
    @Override
    public Context getActContext() {
        return getContext();
    }


    public void showShortToast(@NonNull String message) {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), 0);
        }
        SnackbarUtil.showBarShortTime(getActivity().findViewById(android.R.id.content), message, SnackbarUtil.INFO);
    }

    public void showShortToast(@NonNull String message, int type) {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), 0);
        }
        SnackbarUtil.showBarShortTime(getActivity().findViewById(android.R.id.content), message, type);
    }

    protected void showShortToast(@NonNull String message, @NonNull View.OnClickListener listener, String info) {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), 0);
        }
        SnackbarUtil.showBarShortTime(getActivity().findViewById(android.R.id.content), message, SnackbarUtil.INFO, info, listener);
    }

    public void chooseLocImage() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, Constant.REQUEST_CODE_IMAGE);
    }

    public void chooseLocCamera(String path) {
        File dir = new File(Environment.getExternalStorageDirectory(), "Jh3502/" + path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式在android中，创建文件时，文件名中不能包含“：”冒号
        String filename = df.format(new Date());
        mCamareFile = new File(dir, filename + ".png");
        if (!mCamareFile.exists()) {
            try {
                mCamareFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        selectImageFromCamera(Constant.REQUEST_CODE_CAMERA, mCamareFile);
    }

    public void selectImageFromCamera(int requestCode, @Nullable File saveImage) {
        if (saveImage == null) {
            Log.i(TAG, "Image file parameter is null.");
            saveImage = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".png");
        }
        int currentapiVersion = Build.VERSION.SDK_INT;
        Log.i(TAG, "---currentapiVersion===" + currentapiVersion);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (currentapiVersion < Build.VERSION_CODES.N) {
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(saveImage));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        } else {
            if (saveImage.exists()) {
                try {
                    saveImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.DATA, saveImage.getAbsolutePath());
            Uri uri = mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        startActivityForResult(intent, requestCode);
    }

}
